package repository

import (
	"yak.admin/src/entity"
	"yak.admin/src/util"
)

type RegionRepository struct {
}

func (repository *RegionRepository) FindOneById(id string) (entity.Region, bool)  {
	db := util.GetMysqlPool().Handler()
	region := entity.Region{}
	if num := db.Where("id = ?", id).First(&region).RowsAffected; num > 0 {
		return region, true
	}
	return region, false
}

func (repository *RegionRepository) FindOneByIdAndParentId(id string, parentId string) (entity.Region, bool)  {
	db := util.GetMysqlPool().Handler()
	region := entity.Region{}
	if num := db.Where("id = ? and parent_id = ?", id, parentId).
		First(&region).RowsAffected; num > 0 {
		return region, true
	}
	return region, false
}

func (repository *RegionRepository) PickerLabelsByType(t int) map[string]interface{} {
	var region []*entity.Region
	db := util.GetMysqlPool().Handler()
	if db.Where("type = ?", t).Find(&region).RecordNotFound() {
		return map[string]interface{}{}
	}
	labels := make(map[string]interface{}, len(region))
	for _, m := range region {
		labels[m.Id] = map[string]string {
			"id": m.Id, "name": m.Name, "pid": m.ParentId,
		}
	}
	return labels
}
